<template>
  <div id="contentHolder">
    <video id="video" width="320" height="320" autoplay style="margin-left: 70px"></video>
    <button style="border: #ffffff;width: 100px;height: 30px;margin-left: -190px">
      <input
          type="button"
          id="snap"
          style="width: 100px;height: 30px;margin-left: -5px"
          value="登录"
      />
    </button>


    <canvas style="display: none" id="canvas" width="320" height="320"></canvas>
  </div>
</template>

<script>
import $ from "jquery";

export default {
  name: "loginFace",
  mounted() {
    //这段代码主要是获取摄像头的视频流并显示在Video标签中
    let that=this
    window.addEventListener(
        "DOMContentLoaded",
        function () {
          var canvas = document.getElementById("canvas"),
              context = canvas.getContext("2d"),
              video = document.getElementById("video"),
              videoObj = { video: true },
              errBack = function (error) {
                console.log("Video capture error: ", error.code);
              };
          $("#snap").click(function () {
          //$("#snap").click(function () {
            context.drawImage(video, 0, 0, 330, 250);

            // 搜索
            //登录验证
            var canvans = document.getElementById("canvas");
            // 获取浏览器页面的画布对象
            // 以下开始编 数据
            var imgData = canvans.toDataURL();
            // 将图像转换为base64数据
            var base64Data = imgData.substr(22);
            //开始异步上
            that.$axios
                .post(`http://localhost:9090/loan/admin/verification`, that.$qs.stringify({ img: base64Data })).then(
                response => {
                  console.log('请求成功了', response.data)
                  localStorage.setItem('userName',JSON.stringify(response.data))
                  if (response.data === 'error'){
                    alert("身份验证失败！您还未录入人脸信息");
                  }else{
                    alert("身份验证成功！欢迎您，尊敬的：" + response.data);
                    console.log("成功登录")
                    that.$router.push({name: "admin"})
                  }

                },
                error => {
                  console.log('error submit!!', error.message)
                }
            )

          });
          //navigator.getUserMedia这个写法在Opera中好像是navigator.getUserMedianow
          if (navigator.getUserMedia) {
            navigator.getUserMedia(
                videoObj,
                function (stream) {
                  video.srcObject = stream;
                  video.play();
                },
                errBack
            );
          } else if (navigator.webkitGetUserMedia) {
            navigator.webkitGetUserMedia(
                videoObj,
                function (stream) {
                  video.src = window.webkitURL.createObjectURL(stream);
                  video.play();
                },
                errBack
            );
          }


        },
        false
    );
  },

  methods:{

  }

}
</script>

<style scoped>

</style>